/**
 * LiceoEscazuView.java
 */

 /**
 *  AdSec: Administrador de Secundarias
 *  Copyright (C) 2009 Daniela Ramírez Chaves (dannyrch@gmail.com)
 *  Copyright (C) 2009 Leonel Salazar Valverde (leo87sv@gmail.com)
 *
 *  This file is part of AdSec.
 *  AdSec is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AdSec is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AdSec.  If not, see <http://www.gnu.org/licenses/>.
 */

package adsec.presentacion;

import java.awt.Dimension;
import java.awt.EventQueue;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import adsec.negocios.AdministradorSeguridad;
import adsec.negocios.UtilidadesCapaNegocios;

/**
 * The application's main frame.
 */
public class LiceoEscazuView extends FrameView{

    private LoginDialog login;
    private HiloIconos hiloIconos;


    public LiceoEscazuView(SingleFrameApplication app) {
        super(app);
        this.getFrame().setSize(900, 600);
        this.getFrame().setMinimumSize(new Dimension(900,600));
        hiloIconos = new HiloIconos();

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
    }//fin de constructor

    @Action
    public void realizarLogin(){
        this.mostrarLogin();
        this.habilitarModulos();
        this.panelScrollContenido.setViewportView(null);
    }//fin de realizarLogin

    public void mostrarLogin(){
        login = new LoginDialog(this.getFrame(), true);
        login.setVisible(true);
    }//fin de mostrarLogin

    public void habilitarModulos(){
        AdministradorSeguridad adminSeguridad = AdministradorSeguridad.getInstancia();
        this.btnEstudiantes.setEnabled(
                adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloEstudiantes).isConsultar()
                || adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloMateriasMatriculadas).isConsultar()
                || adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloRegistroNotas).isConsultar()
                || adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloResponsables).isConsultar()
                || adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloReciboMatricula).isConsultar()
                );
        this.btnDocentes.setEnabled(
                adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloDocente).isConsultar()
                || adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloDocenteImparte).isConsultar()
                );
        this.btnNivelSeccion.setEnabled(
                adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloSecciones).isConsultar()
                || adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloNiveles).isConsultar());
        this.btnMaterias.setEnabled(adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloMaterias).isConsultar());
        this.btnAsistencia.setEnabled(adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloAsistencia).isConsultar());
        this.btnPersonalAdm.setEnabled(adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloPersonalAdm).isConsultar());
        this.btnComite.setEnabled(adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloComite).isConsultar());
        this.btnReportes.setEnabled(adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloReportes).isConsultar());
        this.btnUsuariosPerfiles.setEnabled(
                adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloUsuarios).isConsultar()
                || adminSeguridad.getPermiso(UtilidadesCapaNegocios.moduloPerfiles).isConsultar()
                );
    }//fin de habilitarModulos

	public void animar(){
		this.animar("");
	}
	
    public void animar(String mensaje){
        if(!hiloIconos.isAlive()){
            hiloIconos = new HiloIconos(mensaje);
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    hiloIconos.start();
                }
            });
        }//fin de if
        else{
            hiloIconos.detener();
            this.animar();
        }
    }

    public void detenerAnimacion(){
        if(hiloIconos.isAlive()){
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    hiloIconos.detener();
                }
            });
        }//fin de if
    }

    private class HiloIconos extends Thread{
        private boolean continuar = true;
		private String mensaje;

		public HiloIconos(){
			mensaje = "";
		}

		public HiloIconos(String mensajeStatus){
			mensaje = mensajeStatus;
		}

        @Override
        public void run(){
			statusMessageLabel.setText(mensaje);
            while(continuar){
                for(int i = 0; i < busyIcons.length; i++){
                    statusAnimationLabel.setIcon(busyIcons[i]);
                    try{
                        HiloIconos.sleep(50);
                    }catch(InterruptedException e){
                    }
                }
            }//fin de while
            statusAnimationLabel.setIcon(idleIcon);
			statusMessageLabel.setText("");
        }//fin de run

        public void detener(){
            this.continuar = false;
        }

        public boolean estaCorriendo(){
            return this.continuar;
        }
    }//fin de clase HiloIconos

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = LiceoEscazuApp.getApplication().getMainFrame();
            aboutBox = new LiceoEscazuAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        LiceoEscazuApp.getApplication().show(aboutBox);
    }

    @Action
    public void mostrarPanelNivelSeccion(){
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Niveles y Secciones");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
				PanelNivelSeccion panelNivelSeccion = new PanelNivelSeccion();
                panelScrollContenido.setViewportView(panelNivelSeccion);
                hilos.detener();
            }
        });
    }

    @Action
    public void mostrarPanelEstudiantes(){
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Estudiantes");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
				PanelModuloEstudiantes panelEstudiantes = new PanelModuloEstudiantes();
                panelScrollContenido.setViewportView(panelEstudiantes);
                hilos.detener();
            }
        });
    }
    
    @Action
    public void mostrarPanelUsuariosPerfiles() {
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Usuarios y Perfiles");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
				PanelUsuariosPerfiles panelUsuariosPerfiles = new PanelUsuariosPerfiles();
                panelScrollContenido.setViewportView(panelUsuariosPerfiles);
                hilos.detener();
            }
        });
    }

    @Action
    public void mostrarPanelDocentes() {
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Docentes");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
				PanelModuloDocentes panelDocentes = new PanelModuloDocentes();
                panelScrollContenido.setViewportView(panelDocentes);
                hilos.detener();
            }
        });
        
    }

    @Action
    public void mostrarPanelPersonalAdministrativo() {
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Personal Administrativo");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                PanelPersonalAdministrativo panelPersonalAdministrativo = new PanelPersonalAdministrativo();
                panelScrollContenido.setViewportView(panelPersonalAdministrativo);
                hilos.detener();
            }
        });
    }


    @Action
    public void mostrarPanelAsistencia() {
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Asistencia");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                PanelAsistencia panelAsistencia = new PanelAsistencia();
                panelScrollContenido.setViewportView(panelAsistencia);
                hilos.detener();
            }
        });
    }

    @Action
    public void mostrarPanelMaterias() {
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Materias");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                PanelModuloMaterias panelModuloMaterias = new PanelModuloMaterias();
                panelScrollContenido.setViewportView(panelModuloMaterias);
                hilos.detener();
            }
        });
    }

    @Action
    public void mostrarPanelComite() {
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Comités");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                PanelComite panelComite = new PanelComite();
                panelScrollContenido.setViewportView(panelComite);
                hilos.detener();
            }
        });
    }

    @Action
    public void mostrarPanelReportes() {
        final HiloIconos hilos = new HiloIconos("Cargando módulo de Reportes");
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                PanelReportes reportes = new PanelReportes();
                panelScrollContenido.setViewportView(reportes);
                hilos.detener();
            }
        });
    }

    @Action
    public void mostrarPanelConfiguracion() {
        final HiloIconos hilos = new HiloIconos();
        hilos.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                PanelConfiguracion panelConfiguracion = new PanelConfiguracion();
                panelScrollContenido.setViewportView(panelConfiguracion);
                hilos.detener();
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        panelScrollBotones = new javax.swing.JScrollPane();
        panelBotones = new javax.swing.JPanel();
        btnEstudiantes = new javax.swing.JToggleButton();
        btnDocentes = new javax.swing.JToggleButton();
        btnNivelSeccion = new javax.swing.JToggleButton();
        btnMaterias = new javax.swing.JToggleButton();
        btnAsistencia = new javax.swing.JToggleButton();
        btnPersonalAdm = new javax.swing.JToggleButton();
        btnComite = new javax.swing.JToggleButton();
        btnReportes = new javax.swing.JToggleButton();
        btnUsuariosPerfiles = new javax.swing.JToggleButton();
        panelScrollContenido = new javax.swing.JScrollPane();
        barraMenu = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        mitemIniciarSesion = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        btngroupModulos = new javax.swing.ButtonGroup();

        mainPanel.setMinimumSize(new java.awt.Dimension(800, 600));
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(800, 600));

        panelScrollBotones.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        panelScrollBotones.setName("panelScrollBotones"); // NOI18N

        panelBotones.setMinimumSize(new java.awt.Dimension(120, 230));
        panelBotones.setName("panelBotones"); // NOI18N
        panelBotones.setPreferredSize(new java.awt.Dimension(120, 230));
        panelBotones.setLayout(new java.awt.GridLayout(0, 1, 0, 5));

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(adsec.presentacion.LiceoEscazuApp.class).getContext().getActionMap(LiceoEscazuView.class, this);
        btnEstudiantes.setAction(actionMap.get("mostrarPanelEstudiantes")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(adsec.presentacion.LiceoEscazuApp.class).getContext().getResourceMap(LiceoEscazuView.class);
        btnEstudiantes.setText(resourceMap.getString("btnEstudiantes.text")); // NOI18N
        btnEstudiantes.setName("btnEstudiantes"); // NOI18N
        panelBotones.add(btnEstudiantes);

        btnDocentes.setAction(actionMap.get("mostrarPanelDocentes")); // NOI18N
        btnDocentes.setText(resourceMap.getString("btnDocentes.text")); // NOI18N
        btnDocentes.setName("btnDocentes"); // NOI18N
        panelBotones.add(btnDocentes);

        btnNivelSeccion.setAction(actionMap.get("mostrarPanelNivelSeccion")); // NOI18N
        btnNivelSeccion.setText(resourceMap.getString("btnNivelSeccion.text")); // NOI18N
        btnNivelSeccion.setName("btnNivelSeccion"); // NOI18N
        panelBotones.add(btnNivelSeccion);

        btnMaterias.setAction(actionMap.get("mostrarPanelMaterias")); // NOI18N
        btnMaterias.setText(resourceMap.getString("btnMaterias.text")); // NOI18N
        btnMaterias.setName("btnMaterias"); // NOI18N
        panelBotones.add(btnMaterias);

        btnAsistencia.setAction(actionMap.get("mostrarPanelAsistencia")); // NOI18N
        btnAsistencia.setText(resourceMap.getString("btnAsistencia.text")); // NOI18N
        btnAsistencia.setName("btnAsistencia"); // NOI18N
        panelBotones.add(btnAsistencia);

        btnPersonalAdm.setAction(actionMap.get("mostrarPanelPersonalAdministrativo")); // NOI18N
        btnPersonalAdm.setText(resourceMap.getString("btnPersonalAdm.text")); // NOI18N
        btnPersonalAdm.setName("btnPersonalAdm"); // NOI18N
        panelBotones.add(btnPersonalAdm);

        btnComite.setAction(actionMap.get("mostrarPanelComite")); // NOI18N
        btnComite.setText(resourceMap.getString("btnComite.text")); // NOI18N
        btnComite.setName("btnComite"); // NOI18N
        panelBotones.add(btnComite);

        btnReportes.setAction(actionMap.get("mostrarPanelReportes")); // NOI18N
        btnReportes.setText(resourceMap.getString("btnReportes.text")); // NOI18N
        btnReportes.setName("btnReportes"); // NOI18N
        panelBotones.add(btnReportes);

        btnUsuariosPerfiles.setAction(actionMap.get("mostrarPanelUsuariosPerfiles")); // NOI18N
        btnUsuariosPerfiles.setText(resourceMap.getString("btnUsuariosPerfiles.text")); // NOI18N
        btnUsuariosPerfiles.setName("btnUsuariosPerfiles"); // NOI18N
        panelBotones.add(btnUsuariosPerfiles);

        panelScrollBotones.setViewportView(panelBotones);

        panelScrollContenido.setName("panelScrollContenido"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(panelScrollBotones, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelScrollContenido, javax.swing.GroupLayout.DEFAULT_SIZE, 658, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelScrollBotones, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
            .addComponent(panelScrollContenido, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
        );

        barraMenu.setName("barraMenu"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        mitemIniciarSesion.setAction(actionMap.get("realizarLogin")); // NOI18N
        mitemIniciarSesion.setText(resourceMap.getString("mitemIniciarSesion.text")); // NOI18N
        mitemIniciarSesion.setName("mitemIniciarSesion"); // NOI18N
        fileMenu.add(mitemIniciarSesion);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        barraMenu.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        barraMenu.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addContainerGap(776, Short.MAX_VALUE)
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusAnimationLabel)
                    .addComponent(statusMessageLabel))
                .addContainerGap())
        );

        btngroupModulos.add(this.btnEstudiantes);
        btngroupModulos.add(this.btnDocentes);
        btngroupModulos.add(this.btnNivelSeccion);
        btngroupModulos.add(this.btnMaterias);
        btngroupModulos.add(this.btnAsistencia);
        btngroupModulos.add(this.btnPersonalAdm);
        btngroupModulos.add(this.btnComite);
        btngroupModulos.add(this.btnReportes);
        btngroupModulos.add(this.btnUsuariosPerfiles);

        setComponent(mainPanel);
        setMenuBar(barraMenu);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuBar barraMenu;
    private javax.swing.JToggleButton btnAsistencia;
    private javax.swing.JToggleButton btnComite;
    private javax.swing.JToggleButton btnDocentes;
    private javax.swing.JToggleButton btnEstudiantes;
    private javax.swing.JToggleButton btnMaterias;
    private javax.swing.JToggleButton btnNivelSeccion;
    private javax.swing.JToggleButton btnPersonalAdm;
    private javax.swing.JToggleButton btnReportes;
    private javax.swing.JToggleButton btnUsuariosPerfiles;
    private javax.swing.ButtonGroup btngroupModulos;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuItem mitemIniciarSesion;
    private javax.swing.JPanel panelBotones;
    private javax.swing.JScrollPane panelScrollBotones;
    private javax.swing.JScrollPane panelScrollContenido;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}
